<?php
class QuizController extends MainController implements ControllerInterface {


	private static $listType = '__list_type__';

	/**
	 * Strona glowna
	 *
	 */

	public $tableConfig = array(
		'products_list' => array(
			'o' => array(
				'name' => 'product_description.name',
				'popularity' => 'product.popularity',
				'rate' => 'product.rate',
				'brand' => 'manufacturer.name',
				'rank'	=> 'product.rank',
				'_' => 'rank'

			),
			'v' => 'a',
			't' => 10
		)
	);

	protected $tables = array(
		'products_list' => array(
			'o' => array(
				'name' => 'product_description.name',
				'popularity' => 'product.popularity',
				'rate' => 'product.rate',
				'brand' => 'manufacturer.name',
				'_' => 'rate',
			),
			'v' => 'a',
			't' => 10
		)
	); 

	private function rememberQuiz() {
		$remembered = Sessionproxy::GetValue('registration_quiz');
		$remembered = unserialize($remembered);
		if(!is_array($remembered))$remembered = array();

		$remembered = array_merge($remembered, Request::GetAllPost());

		SessionProxy::SetValue('registration_quiz',serialize($remembered));
	}

	private function ClearQuiz() {
		SessionProxy::ClearValue('registration_quiz');
	}

	private function getQuiz() {
		$remembered = Sessionproxy::GetValue('registration_quiz');
		$remembered = unserialize($remembered);
		if(!is_array($remembered))$remembered = array();

		
		return $remembered;
	}



	public function preDispatch($param) {
		$this->Run($param);
	}

	public function postDispatch($param) {
		$this->RunShared('Header',$param);
		$this->RunShared('Footer',$param);
		$this->AddScript('jquery-validate/jquery.validate.js');
	}

	public function IndexAction($param) {

	}

	public function RegistrationQuizStep1Action($param) {
		
		$this->AddStyle(URL_STATIC_CONTENT . '/css/lightbox/prettyPhoto.css');

		$this->AddScript('jquery.prettyPhoto.js');
		$this->AddScript('jquery.MFcropper.js');		
		
		$this->AddTitle($this->t('Registration Quiz 1 Title'));
		$this->AddDescription($this->t('Registration Quiz 1 Description'));
		$this->AddBreadCrumb($this->t('Registration Quiz 1 Title'));
		
		$data = SessionProxy::GetValue('registration_quiz', serialize(array()));
		$data = unserialize($data);
		
		$this->smarty->assign('inputData', $data);
		$this->rememberQuiz();
		
	}

	public function RegistrationQuizStep2Action($param) {
		$this->AddTitle($this->t('Registration Quiz 2 Title'));
		$this->AddDescription($this->t('Registration Quiz 2 Description'));
		$this->AddBreadCrumb($this->t('Registration Quiz 2 Title'));
		$data = SessionProxy::GetValue('registration_quiz', array());
		$data = unserialize($data);
		
		$this->smarty->assign('inputData', $data);	
		$this->rememberQuiz();
	
	}

	public function RegistrationQuizStep3Action($param) {
		$this->AddTitle($this->t('Registration Quiz 3 Title'));
		$this->AddDescription($this->t('Registration Quiz 3 Description'));
		$this->AddBreadCrumb($this->t('Registration Quiz 3 Title'));
		switch(Registry::Get('METRIC_SYSTEM_TYPE'))
		{
			case 1:
				$sizes = Config::Get('us_shoe_size');
				$sizes = explode(';', $sizes[0]);
				$this->smarty->assign('shoeSize', $sizes);
				
				$gripSizes = Config::Get('us_grip_size');
				$gripSizes = explode(';', $gripSizes[0]);
				$this->smarty->assign('gripSize', $gripSizes);
				
				$apparelSizes = Config::Get('us_apparel_size');
				$apparelSizes = explode(';', $apparelSizes[0]);
				$this->smarty->assign('apparelSize', $apparelSizes);				
				break;
			
			case 0:
			default:
				$sizes = Config::Get('eu_shoe_size');
				$sizes = explode(';', $sizes[0]);
				$this->smarty->assign('shoeSize', $sizes);	
				
				$gripSizes = Config::Get('eu_grip_size');
				$gripSizes = explode(';', $gripSizes[0]);
				$this->smarty->assign('gripSize', $gripSizes);	
				
				$apparelSizes = Config::Get('eu_apparel_size');
				$apparelSizes = explode(';', $apparelSizes[0]);
				$this->smarty->assign('apparelSize', $apparelSizes);					
				break;
		}
		$data = SessionProxy::GetValue('registration_quiz', array());
		$data = unserialize($data);
		
		$this->smarty->assign('inputData', $data);			
		
		$this->rememberQuiz();	
	}

	public function RegistrationQuizFinalAction($param) {
		$this->setNoRender();

		$this->rememberQuiz();

		if($this->userLoggedIn) {
			$data = $this->getQuiz();

			$this->RunModule('Quiz','SaveRegistrationQuizData',array('user' => $this->user->getId(), 'data' => $data));
			$this->clearQuiz();
			if(Registry::Get('_redirect_to_premium_'))
			{
				return $this->AddRedirect(Router::GenerateUrl('buyPremium'), 0);
			} else {
				return $this->AddRedirect(Router::GenerateUrl('editProfile'), 0);
			}
		}else{
			$this->addRedirect(Router::GenerateUrl('signIn'),0);
		}
	}

	public function SaveRegistrationQuizData($param) {
		$user = UserDAL::GetResult(UserDAL::GetDalDataObj(array('condition'=>array('id'=>$param['user']))));
		$data = $param['data'];

		$user = $user[0];
		
		$obj = UserExtendedProfileDAL::GetResult(
						UserExtendedProfileDAL::GetDalDataObj(
								array(
									'condition' => array(
										'id_user' => array($user->getId())
									)
								)
						)
		);

		if (empty($obj)) {
			$obj = new UserExtendedProfile();
			$obj->setIdUser($user->getId());
		} else {
			$obj = $obj[0];
		}		
		
		$user->setGender($data['sex']=='male'?1:2);
		if (!empty($data['year']) && !empty($data['month']) && !empty($data['day'])) {
			$user->setBirthDate($data['year'] . '-' . $data['month'] . '-' . $data['day']);
		} else {
			$user->setBirthDate(null);
		}
		if (!empty($data['country'])) {
			$user->setLocation($data['country']);
		} else {
			$user->setLocation(null);
		}
		if (!empty($data['state'])) {
			$user->setState($data['state']);
		} else {
			$user->setState(null);
		}
		if (!empty($data['city'])) {
			$user->setCity($data['city']);
		} else {
			$user->setCity(null);
		}		
		
		if (!empty($data['weight'])) {
			$user->setWeight($data['weight']);
		} else {
			$user->setWeight(null);
		}
		if (!empty($data['height'])) {
			$user->setHeight($data['height']);
		} else {
			$user->setHeight(null);
		}		
		if (isset($data['grip_size'])) {
			$obj->setGripSize($data['grip_size']);
		} else {
			$obj->setGripSize(null);
		}
		if (isset($data['shoe_size'])) {
			$obj->setShoeSize($data['shoe_size']);
		} else {
			$obj->setShoeSize(null);
		}
		if (isset($data['apparel_size'])) {
			$obj->setApparelSize($data['apparel_size']);
		} else {
			$obj->setApparelSize(null);
		}
		if (isset($data['hand'])) {
			$obj->setHand($data['hand']);
		} else {
			$obj->setHand(null);
		}
		if (isset($data['forehand'])) {
			$obj->setForehand($data['forehand']);
		} else {
			$obj->setForehand(null);
		}
		if (isset($data['backhand'])) {
			$obj->setBackhand($data['backhand']);
		} else {
			$obj->setBackhand(null);
		}
		if (isset($data['player_style'])) {
			$obj->setPlayerStyle($data['player_style']);
		} else {
			$obj->setPlayerStyle(null);
		}
		if (isset($data['average_1'])) {
			$obj->setAverage1($data['average_1']);
		} else {
			$obj->setAverage1(null);
		}
		if (isset($data['average_2'])) {
			$obj->setAverage2($data['average_2']);
		} else {
			$obj->setAverage2(null);
		}
		if (isset($data['prefered_court_surface'])) {
			$obj->setPreferedCourtSurface($data['prefered_court_surface']);
		} else {
			$obj->setPreferedCourtSurface(null);
		}
		if (isset($data['top_player'])) {
			$obj->setTopPlayer($data['top_player']);
		} else {
			$obj->setTopPlayer(null);
		}
		if (isset($data['tournament'])) {
			$obj->setTournament($data['tournament']);
		} else {
			$obj->setTournament(null);
		}	
		if(isset($data['ntrp']))
		{
			$obj->setNtrp($data['ntrp']);
		} else {
			$obj->setNtrp(1);
		}
		
		UserExtendedProfileDAL::Save($obj->GetDalDataObj());
		UserDAL::Save($user->getDalDataObj());	
		// racquet, apparel etc
		if(isset($data['racquetId']) && !empty($data['racquetId']))
		{
			$userEq = new UserEquipment();
			$userEq->setIdProduct($data['racquetId']);
			$userEq->setIdUser($user->getId());
			UserEquipmentDAL::Insert($userEq->GetDalDataObj());
		}
		
		$_premium = (bool)$data['premium'];
		Registry::Set('_redirect_to_premium_', $_premium);
		return;

	}

	public function QuickRocketFinderAction($param) {
		$this->addDescription($this->t('Quick Rocket Finder'));
		$this->addTitle($this->t('Quick Rocket Finder'));
		$this->addBreadCrumb($this->t('Quick Rocket Finder'));

		if($this->userLoggedIn) {
			$extendedProfile = UserExtendedProfileDAL::GetResult(UserExtendedProfileDAL::GetDalDataObj(array(
				'condition' => array(
					'id_user' => $this->user->getId()
				),
				'limit' => 1
			)));

			if(isset($extendedProfile[0])) {
				$extendedProfile = $extendedProfile[0];
			}else{
				$extendedProfile = new UserExtendedProfile();
			}

			$this->user->setUserExtendedProfile($extendedProfile);
			$this->smarty->assign('_user',$this->user);
		}
	}

	public function QuickRocketFinderResultsAction($param) {
		$this->addDescription($this->t('Quick Rocket Finder'));
		$this->addTitle($this->t('Quick Rocket Finder'));
		$this->addBreadCrumb($this->t('Quick Rocket Finder'));

		if(Request::IsPost()) {
			$data = Request::GetAllPost();

			if(!$this->userLoggedIn) {
				
				foreach($data AS $k => $v) {
					setcookie('qrf_'.$k, $v, strtotime('+1 month'));
				}
				setcookie('qrf_taken', date('Y-m-d'), strtotime('+1 month'));
				setcookie('qrf_proposal',1, strtotime('+1 month'));
			}

			$idNTRP = Config::Get('ntrp_property_id');
			/*$categoryObj = CategoryDAL::GetResult(CategoryDAL::GetDalDataObj(array(
				'condition' => array(
					'id_category' => array(array(
						'condition' => ' IN ',
						'value' => ' (SELECT id_category FROM product INNER JOIN property_value p ON(p.id_product = product.id_product AND p.id_property IN ('.$idNTRP[0].') AND p.value= '.$data['ntrp'].' ))'
					))
				),
				'groupBy' => 'id_category',
				'sortBy' => 'COUNT(id_category) DESC',
				'limit' => 1
			)));*/
			
			$products = ProductDAL::GetResult(ProductDAL::GetDalDataObj(array(
				'join' => array(
					'PropertyValue p' =>  ' INNER JOIN property_value p ON(p.id_product = product.id_product AND p.id_property IN ('.$idNTRP[0].') AND p.value= '.$data['ntrp'].' )',
					'Category' => ' LEFT JOIN category USING(id_category)'
				),
				'groupBy' => 'product.id_product'
			)));

			$found = array(0);
			$categories = array();

			foreach($products as $product) {
				$categories[$product->category->getId()][] = $product->category;
				$found[] = $product->getId();
			}

			usort($categories,  create_function('$a,$b', 'return count($a) > count($b)?1:-1;'));


			$categoryObj = array_shift($categories);

			$tplData = array();

			$tplData['product_ids'] = implode(',',$found);

			$this->smarty->assign('postData',$tplData);

			$url = Router::GenerateUrl('default');

			if(isset($categoryObj[0])) {
				$parent = CategoryDAL::GetResult(CategoryDAL::getDalDataObj(array(
					'condition' => array(
						'id_category' => $categoryObj[0]->getParent()
					),
					'limit' => 1
				)));

				if(isset($parent[0])) {
					$url = Router::GenerateUrl('mainCategoryView',array('categoryKey' => $parent[0]->getSlug(), 'subCategoryKey' => $categoryObj[0]->getSlug()));
				}
			}

			$this->smarty->Assign('url',$url);
			
		}else{
			$this->addRedirect(Router::GenerateUrl('quizQuickRocketFinder'),0);
			return;
		}
//		if($this->userLoggedIn) {
//			$extendedProfile = UserExtendedProfileDAL::GetResult(UserExtendedProfileDAL::GetDalDataObj(array(
//				'condition' => array(
//					'id_user' => $this->user->getId()
//				),
//				'limit' => 1
//			)));
//
//			if(isset($extendedProfile[0])) {
//				$extendedProfile = $extendedProfile[0];
//			}else{
//				$extendedProfile = new UserExtendedProfile();
//			}
//
//			$this->user->setUserExtendedProfile($extendedProfile);
//			$this->smarty->assign('_user',$this->user);
//		}
	}
}



